/*
 * @lc app=leetcode.cn id=23 lang=golang
 *
 * [23] 合并K个升序链表
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */

import "math"

func mergeKLists(lists []*ListNode) *ListNode {
	root := &ListNode{0, nil}
	head := root
	k := 0
	n := len(lists)
	for k != n {
		k = 0
		var tmp *ListNode
		a := math.MaxInt32
		index := -1
		for i, v := range lists {
			if v != nil {
				if v.Val < a {
					index = i
					a = v.Val
				}
				continue
			} else {
				k++
				continue
			}
		}
		if index < 0 {
			continue
		}
		if k == n-1 {
			head.Next = lists[index]
			break
		}
		tmp = lists[index]
		head.Next = tmp
		head = head.Next
		lists[index] = lists[index].Next

	}
	return root.Next
}

// @lc code=end
